package moltencore.network.protocol;

import spark.network.protocol.Base;
import spark.network.Util;

public class GameEndedNotification extends Base {
	public static class Result {
		long fieldId;
		private static final int FIELD_ID_OFFSET = 0;
		private static final int FIELD_ID_LENGTH = Long.SIZE / 8;
		byte won;
		@SuppressWarnings({"PointlessArithmeticExpression"})
		private static final int WON_OFFSET = FIELD_ID_OFFSET + FIELD_ID_LENGTH;
		private static final int WON_LENGTH = Byte.SIZE / 8;
		private static final int SIZE = FIELD_ID_LENGTH + WON_LENGTH;

		public long getFieldId() {
			return fieldId;
		}

		public void setFieldId(long fieldId) {
			this.fieldId = fieldId;
		}

		public boolean getWon() {
			return won != 0;
		}

		public void setWon(boolean won) {
			this.won = (byte)((won) ? 1 : 0);
		}
	}
	public static final short TYPE = 0x55;
	private static final byte[] TYPE_BYTES = Util.makeBytes(TYPE);

	private byte resultCount;
	private final static int RESULT_COUNT_OFFSET = Base.SIZE;
	private final static int RESULT_COUNT_LENGTH = Byte.SIZE / 8;
	private Result[] results;
	private final static int RESULTS_OFFSET = RESULT_COUNT_OFFSET + RESULT_COUNT_LENGTH;

	private static final int SIZE =
			Base.SIZE +
	        RESULT_COUNT_LENGTH;

	public GameEndedNotification() {
		super(true, TYPE_BYTES);
	}

	public byte getResultCount() {
		return resultCount;
	}

	public void setResultCount(byte resultCount) {
		this.resultCount = resultCount;
		results = new Result[resultCount];
	}

	public Result[] getResults() {
		return results;
	}

	@Override
	public void getBytes(byte[] buffer) {
		super.getBytes(buffer);
		buffer[RESULT_COUNT_OFFSET] = resultCount;
		for(int i = 0; i < resultCount; i++) {
			//noinspection PointlessArithmeticExpression
			Util.arraycopy(Util.makeBytes(results[i].fieldId), 0, buffer, RESULTS_OFFSET + Result.FIELD_ID_OFFSET + i * Result.SIZE);
			buffer[RESULTS_OFFSET + Result.WON_OFFSET + i * Result.SIZE] = results[i].won;
		}
	}

	@Override
	public void fill(byte[] buffer) {
		super.fill(buffer);
		setResultCount(buffer[RESULT_COUNT_OFFSET]);
		results = new Result[resultCount];
		for(int i = 0; i < resultCount; i++) {
			results[i] = new Result();
			//noinspection PointlessArithmeticExpression
			results[i].fieldId = Util.makeLong(buffer, RESULTS_OFFSET + Result.FIELD_ID_OFFSET + i * Result.SIZE);
			results[i].won = buffer[RESULTS_OFFSET + Result.WON_OFFSET + i * Result.SIZE];
		}
	}

	@Override
	public int getSize() {
		return SIZE + resultCount * Result.SIZE;
	}

	public static GameEndedNotification create(byte[] buffer, long receiveTime) {
		GameEndedNotification packet = new GameEndedNotification();
		packet.fill(buffer);
		packet.setTimeStampReceive(receiveTime);
		return packet;
	}
}